package puzzle.common.loader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import tomoto.util.ArrayUtil;

public class Preprocessor {
	private int m_width;
	private List<String[]> m_lines = new ArrayList<String[]>();
	private String m_separatorPattern;

	public Preprocessor(String separatorPattern) {
		m_separatorPattern = separatorPattern;
	}

	public Preprocessor() {
		this("\\s*");
	}

	public int getWidth() {
		return m_width;
	}

	public int getHeight() {
		return m_lines.size();
	}

	public List<String[]> getLines() {
		return m_lines;
	}

	public void process(Reader r) throws IOException {
		BufferedReader br = new BufferedReader(r);
		m_lines.clear();
		m_width = 0;
		for (String line; (line = br.readLine()) != null;) {
			if (line.startsWith("#") || line.length() == 0) {
				continue;
			}

			String[] fields = eliminateEmptyItems(line.split(m_separatorPattern));

			m_width = Math.max(m_width, fields.length);
			m_lines.add(fields);
		}
	}

	private String[] eliminateEmptyItems(String[] splitLine) {
		String[] result = new String[splitLine.length];
		int i = 0;
		for (String item : splitLine) {
			if (item.length() > 0) {
				result[i++] = item;
			}
		}
		return i == splitLine.length ? result : ArrayUtil.dup(result, i);
	}

}
